import { Color } from 'https://unpkg.com/three/build/three.module.js';
import { initShaders } from '../jsm/Utils.js';
import lib from '../jsm/ThreeLib.js';
import Compose from '../jsm/Compose.js';
import Track from '../jsm/Track.js';

window.onload = function () {

    const backColor = new Color("rgba(0,0,0,1)");

    const canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const gl = canvas.getContext("webgl");
    //开启颜色合成,才会有透明度的感觉
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

    //初始化着色器
    initShaders(gl,
        document.querySelector("#vertexShader").innerText,
        document.querySelector("#fragmentShader").innerText);

    lib.clearCanvas(gl, backColor, 0);

    const a_Position = gl.getAttribLocation(gl.program, "a_Position");
    const a_PointSize = gl.getAttribLocation(gl.program, "a_PointSize");
    const u_FragColor = gl.getUniformLocation(gl.program, "u_FragColor");

    const compose = new Compose();
    const stars = [];


    canvas.addEventListener("click", function (event) {
        const { clientX, clientY } = event;
        const { left, top, width, height } = canvas.getBoundingClientRect();
        const [cssX, cssY] = [clientX - left, clientY - top];

        const [x, y] = [lib.GetPosiOfX(width, cssX), lib.GetPosiOfY(height, cssY)];

        const size = Math.floor((Math.random() * (30)) + 20)
        const color = [0, 0, 1, Math.random()]
        const a = 1;
        const obj = { x, y, size, a };
        stars.push(obj);

        const track = new Track(obj);
        track.start = new Date();
        track.timeLen = 2000;
        track.loop = true;
        track.keyMap = new Map([
            [
                'a',
                [
                    [500, a],
                    [1000, 0],
                    [1500, a],
                ]
            ]
        ]);
        compose.add(track);



    })

    !(function ani() {
        compose.update(new Date());
        render();
        requestAnimationFrame(ani);
    })();



    function render() {
        lib.clearCanvas(gl, backColor, 0);
        stars.forEach(({ x, y, size, a }) => {
            gl.vertexAttrib3f(a_Position, x, y, 0.0);
            gl.vertexAttrib1f(a_PointSize, size);
            gl.uniform4f(u_FragColor, 0, 0, 0, a);
            //每次调用该函数都会清除绘制缓冲区,所以需要重头开始绘制一次
            gl.drawArrays(gl.POINTS, 0, 1);
        });
    }

}